import React from 'react'
import { StyleSheet, View, Text } from 'react-native'
import Carousel from 'react-native-snap-carousel'
import { ScaleS, ScaleT, WIDTH, IS_IOS } from 'src/utils/ScreenUtil'
import BasePage from 'src/pageP/base/base-page/index'

import { allFamousList } from 'src/utils/RequestAPI'
import CustomImage from 'src/components/image/CustomImage'
import CustomBoxShadow from 'src/components/boxshadow/CustomBoxShadow'
import { ShowLoading, DismissLoading } from 'src/utils/ToastUtil'
import CustomFlatList from 'src/components/custom-flat-list/index'
import LinearGradient from 'react-native-linear-gradient'
import RefreshState from 'src/components/custom-flat-list/RefreshState'
import { connect } from 'react-redux'
import {
  INIT_USERINFO_ACTION,
  UPDATE_USERINFO_ACTION
} from 'src/store/actions/userinfo'
import CustomButton from 'src/components/button/DebounceButton'
const sliderWidth = WIDTH
const sliderHeight = ScaleS(366)
const itemWidth = ScaleS(306)
const itemHeight = ScaleS(366)
const types = ['companyFinance', 'companyPerson', 'companyAbout']
const SliderWrap = IS_IOS ? CustomBoxShadow : View

// 发送行为
const mapDispatchToProps = dispatch => ({
  updateUserInfo (payload) {
    dispatch(UPDATE_USERINFO_ACTION(payload))
  },
  initUserInfoState () {
    dispatch({
      type: INIT_USERINFO_ACTION
    })
  }
})

@connect(
  ({ userinfo, landmark: { cityName: city } }) => ({
    userId: userinfo.userId,
    city
  }),
  mapDispatchToProps
)
class FamousList extends BasePage {
  constructor (props) {
    super(props)
    this.state = {
      header: {},
      recommend: null,
      recommendActive: 1,
      local: []
    }
  }

  componentDidMount () {
    this._onHeaderRefreshRequest()
  }

  childRender () {
    const { local } = this.state
    return (<CustomFlatList
      ref={this._customFlatListRef}
      style={styles.flatList}
      contentContainerStyle={styles.flatListContent}
      data={local}
      pullDown={true}
      pullUp={false}
      ListHeaderComponent={this._listHeaderComponent}
      onHeaderRefresh={this._onHeaderRefresh}
      keyExtractor={this._keyExtractor}
      renderItem={this._renderItem}
    />
    )
  }

  _onHeaderRefreshRequest= () => {
    const { city } = this.props
    ShowLoading()
    console.log('_onHeaderRefreshRequest')
    return allFamousList({ params: { city } }).then((res) => {
      let { recommend, local } = res.data
      recommend = recommend.map(e => ({
        ...e,
        types: types.map(f => ({
          key: f,
          value: e[f]
        })).filter(f => f.value)
      }))
      local = local.map(e => ({
        ...e,
        types: types.map(f => ({
          key: f,
          value: e[f]
        })).filter(f => f.value)
      }))
      this.setState({
        recommend, local
      })
    }).finally(() => {
      DismissLoading()
    })
  }

  _onHeaderRefresh = () => {
    this.flatListRef.beginHeaderRefresh(RefreshState.Idle)
    this._onHeaderRefreshRequest().then(() => {
      this.flatListRef.endRefreshing(RefreshState.NoMoreData)
    })
  }

  _customFlatListRef = (ref) => {
    this.flatListRef = ref
  }

  _keyExtractor = (item, index) => item.companyId.toString()

  _renderItem = ({ item, index }) => {
    return <CustomBoxShadow style={styles.itemShaow}>
      <CustomButton style={styles.itemBtn} params={item} onPress={this.handleItemClick}>
        <CustomImage style={styles.sliderLogo} source={{ uri: item.logo }} />
        <View style={styles.sliderContent}>
          <Text style={styles.sliderSimpleName} numberOfLines={1}>
            {item.simpleName}
            <Text numberOfLines={1} style={styles.sliderSlogan}>{`   ` + item.slogan}</Text>
          </Text>
          <View style={styles.sliderTypes}>
            {item.types.map(e => (
              <View key={`${item.companyId}${e.key}`} style={styles.sliderType}>
                <Text style={styles.sliderTypeTxt}>{e.value}</Text>
              </View>
            )
            )}
          </View>
          <View style={styles.itemWrap3}>
            <LinearGradient
              start={{ x: 0, y: 1 }}
              end={{ x: 1, y: 0 }}
              colors={['#FF9310', '#FFDC25']}
              style={styles.famousIcon}>
              <Text style={styles.famousText}>名企</Text>
            </LinearGradient>
            <Text style={styles.postCount}>热招职位<Text style={styles.postCountColor}>{item.postCount}</Text>个</Text>
          </View>
        </View>
      </CustomButton>
    </CustomBoxShadow>
  }

  _listHeaderComponent = () => {
    const { recommendActive, recommend } = this.state
    return recommend ? <View style={styles.carouselContainer}>
      <View style={styles.sliderTop}>
        <Text style={styles.bigTitle}>名企推荐</Text>
        <View style={styles.pagination}>
          <Text style={styles.activeText}>{recommendActive}</Text>
          <View style={styles.inactiveBias}/>
          <Text style={styles.inactiveText}>{recommend.length}</Text>
        </View>
      </View>
      <Carousel
        data={recommend}
        renderItem={this._renderItemSwiper}
        onSnapToItem={this.handleSnapToItem}
        sliderWidth={sliderWidth}
        sliderHeight={sliderHeight}
        itemWidth={itemWidth}
        itemHeight={itemHeight}
        activeSlideAlignment={'start'}
        inactiveSlideScale={0.85}
        inactiveSlideOpacity={0.8}
        layout={'default'}
        autoplay={true}
        loop={IS_IOS}
        autoplayInterval={5000}
        enableSnap={true}
        useScrollView={IS_IOS}
      />
      <Text style={styles.bigTitle}>本地名企</Text>
    </View> : null
  }

  _renderItemSwiper = ({ item, index }) => {
    return (
      <SliderWrap style={styles.sliderShadow}>
        <CustomButton style={styles.sliderBtn} params={item} onPress={this.handleItemClick}>
          <CustomImage style={styles.sliderBackground} source={{ uri: item.background }}/>
          <View style={styles.sliderBottom}>
            <CustomImage style={styles.sliderLogo} source={{ uri: item.logo }} />
            <View style={styles.sliderContent}>
              <Text style={styles.sliderSimpleName} numberOfLines={1}>{item.simpleName}<Text numberOfLines={1} style={styles.sliderSlogan}>{`   ` + item.slogan}</Text>
              </Text>
              <View style={styles.sliderTypes}>
                {item.types.map(e => (
                  <View key={`${index}${e.key}`} style={styles.sliderType}><Text style={styles.sliderTypeTxt}>{e.value}</Text></View>
                )
                )}
              </View>
            </View>
          </View>
        </CustomButton>
      </SliderWrap>
    )
  }

  handleSnapToItem = (recommendActive) => {
    console.log('handleSnapToItem', recommendActive)
    this.setState({
      recommendActive: ++recommendActive
    })
  }

  handleItemClick = (item) => {
    console.log('handleItemClick', item)
    this.props.navigation.navigate('CompanyHomepage', {
      companyId: item.companyId,
      famousDisplay: true
    })
  }
}

export default FamousList

const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  carouselContainer: {
    marginTop: ScaleS(20),
    marginBottom: ScaleS(8)
  },
  bigTitle: {
    marginLeft: ScaleS(20),
    fontSize: ScaleT(27),
    fontWeight: '600',
    color: '#444444'
  },
  sliderTop: {
    backgroundColor: 'transparent',
    flexDirection: 'row',
    justifyContent: 'space-between'
  },
  pagination: {
    position: 'relative',
    marginRight: ScaleS(20),
    height: ScaleS(35),
    width: ScaleS(50)
  },
  activeText: {
    position: 'absolute',
    top: 0,
    right: ScaleS(20),
    fontSize: ScaleT(20),
    fontWeight: '600',
    color: '#000000'
  },
  inactiveBias: {
    position: 'absolute',
    top: ScaleS(17),
    right: ScaleS(12),
    transform: [{ rotate: '-45deg' }],
    width: ScaleS(10),
    height: ScaleS(1),
    backgroundColor: '#CCCCCC'
  },
  inactiveText: {
    position: 'absolute',
    bottom: 0,
    right: 0,
    fontSize: ScaleT(20),
    fontWeight: '600',
    color: '#CCCCCC'
  },
  sliderShadow: {
    marginTop: ScaleS(20),
    marginBottom: ScaleS(50),
    marginLeft: ScaleS(20),
    width: ScaleS(306),
    height: ScaleS(366),
    borderRadius: ScaleS(6),
    backgroundColor: '#FFFFFF',
    shadowRadius: ScaleS(15),
    shadowOpacity: 0.1,
    shadowColor: '#000000',
    shadowOffset: {
      width: 0,
      height: ScaleS(3)
    }
  },
  sliderBtn: {
    borderRadius: ScaleS(6),
    overflow: 'hidden',
    width: ScaleS(306),
    height: ScaleS(366),
    flex: 1
  },
  sliderBackground: {
    width: ScaleS(306),
    height: ScaleS(276),
    resizeMode: 'cover'
  },
  sliderBottom: {
    backgroundColor: IS_IOS ? '#FFFFFF' : 'rgba(0,0,0,0.02)',
    flex: 1,
    flexDirection: 'row'
  },
  sliderLogo: {
    resizeMode: 'cover',
    width: ScaleS(38),
    height: ScaleS(38),
    borderRadius: ScaleS(19),
    alignSelf: 'flex-start',
    marginTop: ScaleS(18),
    marginHorizontal: ScaleS(10)
  },
  sliderContent: {
    flex: 1
  },
  sliderSimpleName: {
    marginTop: ScaleS(10),
    fontSize: ScaleT(16),
    fontWeight: '500',
    color: '#000000',
    lineHeight: ScaleS(36)
  },
  sliderSlogan: {
    paddingLeft: ScaleS(12),
    fontSize: ScaleT(12),
    fontWeight: '400',
    color: '#999999'
  },
  sliderTypes: {
    flexDirection: 'row'
  },
  sliderType: {
    marginRight: ScaleS(10),
    minWidth: ScaleS(55),
    height: ScaleS(24),
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: ScaleS(2),
    backgroundColor: 'rgba(216, 216, 216, 0.2)'
  },
  sliderTypeTxt: {
    marginHorizontal: ScaleS(8),
    fontSize: ScaleT(12),
    fontWeight: '400',
    color: '#666666'
  },
  flatListContent: {
    paddingBottom: ScaleS(20)
  },
  itemShaow: {
    marginHorizontal: ScaleS(20),
    marginVertical: ScaleS(8),
    width: ScaleS(335),
    height: ScaleS(130),
    backgroundColor: 'white',
    borderRadius: ScaleS(5),
    shadowRadius: ScaleS(40),
    shadowOpacity: 0.2,
    shadowColor: '#999999',
    shadowOffset: {
      width: 0,
      height: ScaleS(7)
    }
  },
  itemBtn: {
    width: ScaleS(335),
    height: ScaleS(130),
    flexDirection: 'row',
    paddingTop: ScaleS(5)
  },
  itemWrap3: {
    marginTop: ScaleS(15),
    flexDirection: 'row',
    alignItems: 'center'
  },
  famousIcon: {
    width: ScaleS(42),
    height: ScaleS(18),
    marginRight: ScaleS(12),
    borderRadius: ScaleS(8),
    borderBottomLeftRadius: 0,
    justifyContent: 'center',
    alignItems: 'center'
  },
  famousText: {
    color: '#FFFFFF',
    fontWeight: '500',
    fontSize: ScaleT(11)
  },
  postCount: {
    color: '#999999',
    fontWeight: '500',
    fontSize: ScaleT(14)
  },
  postCountColor: {
    color: '#FFC61C'
  }
})
